package com.jz.netthings.engine.sqlite;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.*;

/**
 * 连接sqlite数据库
 */
public class SqliteDbEngine {



    static Logger logger = LoggerFactory.getLogger(SqliteDbEngine.class);

    private static final  String className = "org.sqlite.JDBC";
    /**
     * 数据库连接前缀，自己跟上数据库路径及名称
     */
    private  String dbUrlPrefix = "jdbc:sqlite:";

    private Connection connection;

    static {
        try {
            Class.forName(className);
        }catch (Exception e){
            logger.error("初始化sqlite失败",e);
        }
    }

    public SqliteDbEngine(String dbPath){
        try {
            logger.info("创建Sqlite数据库连接："+ dbUrlPrefix + dbPath);
            this.connection = DriverManager.getConnection(dbUrlPrefix + dbPath);
        }catch (Exception e){
            logger.error("创建Sqlite数据库连接失败",e);
        }
    }

    public void freeConn()throws Exception{
        logger.info("关闭Sqlite数据库连接");
        this.connection.close();
    }

    /**
     * 执行sql
     * @param sql
     * @return
     * @throws SQLException
     * @throws ClassNotFoundException
     */
    public PreparedStatement prepareStatement(String sql) throws SQLException {
        return connection.prepareStatement(sql);
    }

    public static void main(String[] args) throws Exception {
        SqliteDbEngine dbEngine = new SqliteDbEngine("E:\\009_2019-04-02_09-32-43.db.rd");
        PreparedStatement statement = dbEngine.prepareStatement("SELECT * FROM donator");

        ResultSet rs = statement.executeQuery();

        while (rs.next()){
            String id = rs.getString("id");
            String name = rs.getString("name");
            String regcode = rs.getString("regcode");
            String sex = rs.getString("sex");
            int age = rs.getInt("age");
            String address = rs.getString("address");

            System.out.println(id +"："+name +"："+regcode +"："+sex +"："+age +"："+address);
        }

        dbEngine.freeConn();

    }
}
